﻿using System.Collections.Generic;
using System.Collections;
using System;

public class DatabaseJob : IEnumerator
{
    protected SqliteDatabase database;
    protected string query;
    protected ThreadJob threadJob;
    protected DataTable result;

    public DatabaseJob(SqliteDatabase database, string query)
    {
        this.database = database;
        this.query = query;
    }

    public virtual void StartJob()
    {

    }

    public object Current
    {
        get
        {
            if (threadJob == null)
                return null;
            return threadJob.Current;
        }
    }
    public bool MoveNext()
    {
        if (threadJob == null)
            return true;
        return threadJob.MoveNext();
    }

    public void Reset()
    {
    }
}

public class DatabaseQueryJob : DatabaseJob
{
    public DatabaseQueryJob(SqliteDatabase database, string query) :base(database, query)
    {
    }

    public override void StartJob()
    {
        threadJob = AppFacade.threadManager.SetJob(() =>
        {
            return database.ExecuteQuery(query);
        });
    }
}

public class DatabaseNonQueryJob : DatabaseJob
{
    public DatabaseNonQueryJob(SqliteDatabase database, string query) : base(database, query)
    {
    }

    public override void StartJob()
    {
        threadJob = AppFacade.threadManager.SetJob(() =>
        {
            database.ExecuteNonQuery(query);
        });
    }
}




public class DatabaseManager: Manager
{
    Queue<DatabaseJob> queryJobs;
    DatabaseJob currentJob;

    private void Awake()
    {
        queryJobs = new Queue<DatabaseJob>();
    }

    private new void Update()
    {
        if(currentJob == null)
        {
            if (queryJobs.Count > 0)
            {

                currentJob = queryJobs.Dequeue();
                currentJob.StartJob();
            }
        }
        else
        {
            if (currentJob.MoveNext() == false)
            {
                currentJob = null;
            }
        }
    }

    public DatabaseJob StartExecuteNonQuery(SqliteDatabase database, string query)
    {
        DatabaseJob job = new DatabaseNonQueryJob(database, query);
        queryJobs.Enqueue(job);
        return job;
    }

    public DatabaseJob StartExecuteQuery(SqliteDatabase database, string query)
    {
        DatabaseJob job = new DatabaseQueryJob(database, query);
        queryJobs.Enqueue(job);
        return job;
    }
}
